package com.im.service;

import com.im.domain.bean.TextMessage;
import com.im.domain.enumtype.MessageType;
import com.im.domain.enumtype.SendType;
import com.im.dao.TextMessageRepository;
import com.im.util.PageJpa;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * Created by 岸芷汀翎 on 2017/1/26.
 * Description:
 */
@Service
public class TextMessageService {
    @Resource
    private TextMessageRepository textMessageDao;

    public void save(TextMessage tm) {
        textMessageDao.save(tm);
    }
    
    public List<TextMessage> getList(String sendId,SendType sendType,MessageType type){
    	return textMessageDao.getListByParam(sendId, sendType, type);
    }
    
    public PageJpa<TextMessage> getHistoryChatMessage(PageJpa<TextMessage> page){
    	TextMessage param = page.getObj();
    	if(StringUtils.isEmpty(param.getUserId()) && StringUtils.isEmpty(param.getSendId())){
    		return page;
    	}
    	page.setSortName("timeStamp");
    	page.setSortOrder("desc");
    	return page.getData(textMessageDao, new Specification<TextMessage>() {
			@Override
			public Predicate toPredicate(Root<TextMessage> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				if(MessageType.FRIEND.equals(param.getType())){
					Predicate type = cb.equal(root.get("type"), MessageType.FRIEND);
					Predicate other = cb.or(cb.and(cb.equal(root.get("userId"), param.getUserId()),
							cb.equal(root.get("sendId"), param.getSendId())),
							cb.and(cb.equal(root.get("userId"), param.getSendId()),
									cb.equal(root.get("sendId"), param.getUserId())));
					return cb.and(type,other);
				}else if(MessageType.GROUP.equals(param.getType())){
					Predicate type = cb.equal(root.get("type"), MessageType.GROUP);
					Predicate other = cb.and(cb.equal(root.get("sendId"), param.getSendId()));
					return cb.and(type,other);
				}
				
				return null;
			}
		});
    }
    
    public void cleanDataBeginTime(Date time){
    	if(time != null){
    		textMessageDao.deleteDataByTime(time);
    	}
    }
}
